package com.novartis.nims.util;

import java.io.File;
import java.io.IOException;

import org.apache.log4j.Logger;

import com.pixelmed.dicom.Attribute;
import com.pixelmed.dicom.AttributeList;
import com.pixelmed.dicom.AttributeTag;
import com.pixelmed.dicom.DicomException;
import com.pixelmed.dicom.DicomInputStream;
import com.pixelmed.dicom.TagFromName;

public class DicomHelper {
	
	private static final Logger mLogger = Logger.getRootLogger();
	
	public static AttributeList readDICOMAttributes(File dicomFile, boolean allowBadPixelData) {
		AttributeList list = new AttributeList();
		DicomInputStream dis = null;
		try {
			dis = new DicomInputStream(dicomFile);
			try {
				list.read(dis);
			} catch (DicomException e) {
				if (! allowBadPixelData) return null;
				
				/* exception may be due to truncated pixel data. try stopping the read w/out
				 * processing pixel data or later elements. there are no elements of interest
				 * after pixel data, so this is safe. we processed it in the first place, so
				 * that we can detect this case and issue a warning.
				 */
				
				mLogger.warn(dicomFile.getAbsolutePath() + " may be truncated. Ignoring pixel data and re-trying read.");
				try {
					list.read(dis, TagFromName.PixelData);
				} catch (DicomException de) {
					return null;
				}
			} finally {
				if (dis != null) dis.close();
			}
		} catch (IOException e) {
			return null;
		}
		
		return list;
	}
	

	
	/**
	 * Extract the value of a particular attribute from a list of DICOM attributes.
	 * 
	 * @param list - the list of DICOM attributes to parse
	 * @param tag - the tag describing which attribute to extract
	 * @return null if the attribute wasn't found. an empty string if the attribute
	 * was found but contained no value. otherwise, the string value of the attribute
	 */
	public static String getAttributeValue(AttributeList list, AttributeTag tag) {
		Attribute attr = list.get(tag);
		String value = null;
		if (attr != null) {		
			value = attr.getSingleStringValueOrNull();
		}
		
		return attr == null ? null : (value == null ? "" : value);
	}

}
